package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.commom.PageResult;
import com.itheima.ydd.commom.R;
import com.itheima.ydd.dto.YddArticleDto;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.entity.YddArticle;
import com.itheima.ydd.entity.YddCate;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.*;
import com.itheima.ydd.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 登录管理
 */
@Slf4j
@RestController
@RequestMapping("/index")
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private YddArticleService yddArticleService;
    @Autowired
    private YddCateService yddCateService;

    @Autowired
    private YddUserService yddUserService;


    /**
     * 获取系统配置——这里是登录时首页的系统信息展示
     * @return
     */
    @GetMapping("/getConfig")
    public R getConfig(){

        Map mapConfig = sysConfigService.getSystemConfig();

        return R.success("", mapConfig);
    }

    /**
     * 后台用户登录
     * @param sysUser
     */
    @PostMapping("/login")
    public R login(@RequestBody SysUser sysUser) {
        log.info("当前登录用户为，sysUser:{}",sysUser.toString());
        //密码的md5加密
        String password = sysUser.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        System.out.println(password);

        //判断账户是否存在并验证密码
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysUser::getLoginName , sysUser.getLoginName());
        lqw.eq(SysUser::getPassword , password );

        SysUser user = sysUserService.getOne(lqw);
        if (user == null) {
            return R.error("用户名或密码错误");
        }

        if (user.getStatus() == 0){
            return R.error("账户已被冻结");
        }

        //登录成功，返回token信息
        //处理添加到token中的信息
        Map map = new HashMap();
        map.put("userId",user.getId());
        String roleId = user.getRoleId();
        roleId = roleId.replace("[","")
                .replace("]","");

        map.put("roleId",roleId);


        String token = JwtUtils.getToken(map);
        Map tokenMap = new HashMap();
        tokenMap.put("token",token);
        return R.success("登录成功",tokenMap);
    }


    /**
     * 获取用户资料
     * @param request
     * @return
     */
    @PostMapping("/profile")
    public R profile(HttpServletRequest request){
        String token = request.getHeader("x-token");
        //解析token
        Claims claims = JwtUtils.getClaims(token);
        //获取用户的信息
        Long userId = Long.valueOf((String)claims.get("userId"));

        log.info("当前用户的id为：{}",userId);

        //通过当前用户的id获取信息
        Map mapInfo = sysUserService.getInfo(userId.toString());

        return R.success("",mapInfo);
    }

    /**
     * 获取主页统计信息
     * @return
     */
    @GetMapping("/baseInfo")
    public R getBaseInfo(){
        Map mapInfo =  sysConfigService.getBaseInfo();
        //将获取到的map数据返回给前端
        return R.success("",mapInfo);
    }

    /**首页大列表分页查询
     * api/index/new?page=1&limit=10
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/new")
    @Cacheable(value = "article" , key = "123" , unless = "#result.data == null ")
    public R newPage(int page, int limit){
        log.info("接收的参数为{},{}",page,limit);
        Page<YddArticle> pageInfo = new Page<>(page,limit);

        //创建分页对象查询数据
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddArticle::getIstop,1);
        wrapper.orderByDesc(YddArticle::getCreateDate).orderByDesc(YddArticle::getUpdateDate);
        yddArticleService.page(pageInfo,wrapper);

        //将分页数据添加到对应的page结果集
        PageResult pageResult = new PageResult();
        pageResult.setCurrentPage(pageInfo.getCurrent());
        pageResult.setPageSize(pageInfo.getSize());
        pageResult.setCount(pageInfo.getTotal());
        pageResult.setTotalPages(pageInfo.getPages());
        pageResult.setData(pageInfo.getRecords());

        //创建最终的结果集,把结果封装返回给页面
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("desc","首页大列表");
        resultMap.put("list",pageResult);
        //计算大于一天前的数据有多少条
        Long numDay= new Date().getTime() -1000*60*60*24;
        wrapper.gt(YddArticle::getCreateDate,numDay).or().gt(YddArticle::getUpdateDate,numDay);
        int num_day = yddArticleService.count(wrapper);
        resultMap.put("num_day",(long) num_day);
        //计算大于一周前的数据有多少条
        Long numWeek= new Date().getTime() -1000*60*60*24*7;
        wrapper.gt(YddArticle::getCreateDate,numWeek).or().gt(YddArticle::getUpdateDate,numWeek);
        int num_week = yddArticleService.count(wrapper);
        resultMap.put("num_week",(long) num_week);

        return R.success("",resultMap);
    }



    /**
     * 前台首页和全局数据
     * @return
     */
    @GetMapping("/index")
    public R getIndex(){
        log.info("前台index请求。。。。");
        Map map = sysUserService.index();
        return R.success("", map);
    }

    @GetMapping("/hot")
    public R hot() {
        List<YddCate> list = yddCateService.list();
        List<YddArticle> yddArticles = new ArrayList<>();
        for (YddCate yddCate : list) {
            LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(YddArticle::getCateid, yddCate.getId());
            queryWrapper.eq(YddArticle::getIshot, 1);
            List<YddArticle> list1 = yddArticleService.list(queryWrapper);
            yddArticles.add(list1.get(0));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("desc", "侧边最新新闻");
        map.put("list", yddArticles);
        return R.success("", map);
    }


    /**前台导航栏分类查询
     * index/list?page=1&limit=10&cateid=8
     * @param page
     * @param limit
     * @param cateid
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "article" , key = "#cateid +'_article'" , unless = "#result.data == null ")
    public R list(Integer page,Integer limit,Integer cateid){
        log.info("接收到的参数为page={},limit={},cateid={}",page,limit,cateid);

        //创建分页对象查询结果
        Page<YddArticle> pageInfo = new Page<>(page,limit);
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddArticle::getCateid,cateid);
        wrapper.orderByDesc(YddArticle::getCreateDate);
        yddArticleService.page(pageInfo,wrapper);
        List<YddArticle> records = pageInfo.getRecords();
        List<YddArticleDto> dtoList=records.stream().map((item)->{
            YddArticleDto dto = new YddArticleDto();
            BeanUtils.copyProperties(item,dto);
            YddCate cate = yddCateService.getById(cateid);
            dto.setCatename(cate.getCatename());
            return dto;
        }).collect(Collectors.toList());

        //进一步处理数据:把数据封装到pageResult里面
        PageResult pageResult = new PageResult();
        pageResult.setCount(pageInfo.getTotal());
        pageResult.setTotalPages(pageInfo.getPages());
        pageResult.setPageSize(pageInfo.getSize());
        pageResult.setCurrentPage(pageInfo.getCurrent());
        pageResult.setData(dtoList);

        //创建最终结果集
        Map<String, PageResult> map = new HashMap<>();
        map.put("list",pageResult);

        return R.success("",map);
    }


    /**
     * 前台用户注册
     */
    @PostMapping("reg")
    public R reg(@RequestBody YddUser yddUser) {
        YddUser user = yddUserService.getOne(new LambdaQueryWrapper<YddUser>().eq(YddUser::getMobile, yddUser.getMobile()));
        if (user != null) {
            return R.error("用户已存在");
        }
        yddUser.setPassword(DigestUtils.md5DigestAsHex(yddUser.getPassword().getBytes(StandardCharsets.UTF_8)));
        yddUser.setUsername(yddUser.getMobile());
        yddUserService.save(yddUser);

        Map map = new HashMap();
        map.put("userId", yddUser.getId());

        String token = JwtUtils.getToken(map);
        Map tokenMap = new HashMap();
        tokenMap.put("token", token);

        return R.success("注册成功", tokenMap);
    }

    /**
     * 热门文章
     * @return
     */
    @GetMapping("recommend")
    public R recommend() {
        List<YddArticle> yddArticles = yddArticleService.list(new LambdaQueryWrapper<YddArticle>().orderByDesc(YddArticle::getLovenum).last("limit 6"));
        List<Object> list = new ArrayList<>();
        for (YddArticle yddArticle : yddArticles) {
            Map map = new HashMap<>();
            map.put("catename", yddCateService.getById(yddArticle.getCateid()).getCatename());
            map.put("id", yddArticle.getId());
            map.put("title", yddArticle.getTitle());
            map.put("pic", yddArticle.getPic());
            map.put("click", yddArticle.getClick());
            map.put("lovenum", yddArticle.getLovenum());
            list.add(map);
        }
        HashMap data = new HashMap<>();
        data.put("desc", "侧边推荐文章");
        data.put("list", list);
        return R.success("", data);
    }

    @GetMapping("/show")
    public R show(Integer id) {
        //1、获取本页文章数据
        YddArticle yddArticle1 = yddArticleService.getById(id);
        //2、根据文章表中cateid在cate表中获取catename
        Integer cateid = yddArticle1.getCateid();
        YddCate yddCate = yddCateService.getById(cateid);
        String catename = yddCate.getCatename();//获取catename

        //3、创建返回值data，
        // 3.1当页数据用dto包装，
        YddArticleDto articleDto = new YddArticleDto();
        BeanUtils.copyProperties(yddArticle1,articleDto);//复制数据
        //设置其他数据
        articleDto.setCatename(catename);
        articleDto.setCollect(false);
        articleDto.setLike(false);
        Map<String, Object> map = new HashMap<>();
        map.put("info", articleDto);

        //3.2上一页数据prev,下一页数据next
        ArrayList<Object> next = new ArrayList<>();
        Map<String, Object> next_1 = new HashMap<>();
        next_1.put("id",null);
        next_1.put("title", null);

        String b = "next";
        int a = id + 1;
        for (int i = 0; i < 2; i++) {
            System.out.println(a);
            try {
                YddArticle yddArticle2 = yddArticleService.getById(a);
                next_1.put("id", yddArticle2.getId());
                next_1.put("title", yddArticle2.getTitle());
            } catch (NullPointerException e) {
            }
            a = a - 2;
            next.clear();
            next.add(next_1);
            map.put(b, next);
            b = "prev";
        }
        return R.success("0", map);
    }
}
